<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Vue 3 + Dexie + Element Plus Autocomplete</title>
  <!-- Element Plus 样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    .autocomplete-container {
      max-width: 500px;
      margin: 0 auto;
      padding: 20px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 4px;
    }
  </style>
</head>
<body>
  <div id="app"></div>

  <!-- 引入 Vue 3 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <!-- 引入 Element Plus -->
  <script src="https://unpkg.com/element-plus"></script>
  <!-- 引入 Dexie -->
  <script src="https://unpkg.com/dexie/dist/dexie.js"></script>
  
  <script>
    // 创建 Dexie 数据库
    const db = new Dexie('AutocompleteDatabase');
    db.version(1).stores({
      items: '++id, name, description'
    });

    // 添加一些示例数据
    async function initializeDatabase() {
      // 检查是否已有数据
      const count = await db.items.count();
      if (count > 0) return;
      
      await db.items.bulkPut([
        { name: 'Apple', description: 'A fruit' },
        { name: 'Banana', description: 'Yellow fruit' },
        { name: 'Cherry', description: 'Small red fruit' },
        { name: 'Date', description: 'Sweet fruit' },
        { name: 'Elderberry', description: 'Dark purple berry' },
        { name: 'Fig', description: 'Mediterranean fruit' },
        { name: 'Grape', description: 'Used for wine' },
        { name: 'Honeydew', description: 'Type of melon' },
        { name: 'Iceberg Lettuce', description: 'Crispy lettuce' },
        { name: 'Jackfruit', description: 'Large tropical fruit' },
        { name: 'Kiwi', description: 'Fuzzy brown fruit with green flesh' },
        { name: 'Lemon', description: 'Sour citrus fruit' }
      ]);
    }

    initializeDatabase().catch(err => {
      console.error('Failed to initialize database:', err);
    });

    const { createApp, ref } = Vue;
    const { ElAutocomplete, ElOption } = ElementPlus;

    const app = createApp({
      components: {
        ElAutocomplete,
        ElOption
      },
      setup() {
        const query = ref('');
        const suggestions = ref([]);
        const loading = ref(false);

        // 从 Dexie 搜索数据
        const searchItems = async (queryString, cb) => {
          if (!queryString) {
            suggestions.value = [];
            cb([]);
            return;
          }
          
          loading.value = true;
          try {
            // 使用 Dexie 进行搜索（不区分大小写）
            const results = await db.items
              .where('name')
              .startsWithIgnoreCase(queryString)
              .limit(10)
              .toArray();
            
            suggestions.value = results;
            cb(results);
          } catch (error) {
            console.error('Search error:', error);
            suggestions.value = [];
            cb([]);
          } finally {
            loading.value = false;
          }
        };

        // 处理选择事件
        const handleSelect = (item) => {
          console.log('Selected item:', item);
          // 这里可以添加选择后的逻辑
        };

        return {
          query,
          suggestions,
          loading,
          searchItems,
          handleSelect
        };
      },
      template: `
        <div class="autocomplete-container">
          <h2>Dexie Autocomplete Demo</h2>
          <p>Search for fruits in the database (try "a", "b", etc.)</p >
          <el-autocomplete
            v-model="query"
            :fetch-suggestions="searchItems"
            :loading="loading"
            placeholder="Search items..."
            @select="handleSelect"
            clearable
          >
            <template #default="{ item }">
              <div style="display: flex; justify-content: space-between; width: 100%;">
                <span style="font-weight: bold;">{{ item.name }}</span>
                <span style="color: #999; font-size: 0.9em; margin-left: 10px;">{{ item.description }}</span>
              </div>
            </template>
          </el-autocomplete>
          <div v-if="query" style="margin-top: 20px;">
            <h3>Current query: "{{ query }}"</h3>
            <div v-if="loading">Loading...</div>
            <div v-else>
              <p v-if="suggestions.length === 0">No results found</p >
              <ul v-else>
                <li v-for="item in suggestions" :key="item.id">
                  {{ item.name }} - {{ item.description }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      `
    });

    // 使用 Element Plus
    app.use(ElementPlus);
    app.mount('#app');
  </script>
</body>
</html>